﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using Google.Protobuf.WellKnownTypes;

public abstract class RequestBase
{
    static int cur_seq = 0;
    public static int GetCurReqSeq()
    {
        return System.Threading.Interlocked.Increment(ref cur_seq);
    }

    public MessagePacket MessagePacket;

    /// <summary>
    /// 发送时间，秒
    /// </summary>
    private double m_SendTime;
    public double sendTime=>m_SendTime;

    public float timeOutSeconds = 5;
    
    public ClientSocket clientSocket;

    public abstract ResponseData NewResponseData();

    protected abstract ISerialize requestData { get; }

    public virtual bool needResponse => true;

    public RequestBase()
    {
        MessagePacket = new MessagePacket();// NewMessage();
        MessagePacket.seq = GetCurReqSeq();
        MessagePacket.type = MessagePacketType.Event;
        //Debug.Log("NetRequest seq:"+ message. seq+ "  time:" + message.time);
    }

   // public abstract ResponseBase GetResponseHandler();

    public Action<ResponseBase> onResponse;
    public Action<RequestBase> onTimeOut;


    public void Send()
    {
        if (clientSocket == null)
        {
            Debug.LogError("socketClient == null");
            return;
        }

        if (requestData != null)
            this.MessagePacket.data = requestData.Write();
        
        this.m_SendTime = CommonFunctions.GetTimeStampSeconds();
        
        this.clientSocket.SendRequest(this);

        GameDebug.LogShowy($"Ping send:{Time.time}");

        OnSend();
    }

    public virtual void OnSend() { }

}
